<template>
  <div class="app-container">
    <el-tabs v-model="editableTabsValue" type="border-card" @tab-remove="removeTab" style="padding: 30px 0;">
      <el-tab-pane
        label="缴费列表"
        name="缴费列表"
      >
        <br>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        > 
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="会员编号" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientCode }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientName }}
            </template>
          </el-table-column>
          <el-table-column label="等级" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.vipLevel }}
            </template>
          </el-table-column>
          <el-table-column label="就诊方式" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.typeName }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="就诊医生" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.doctorName }}
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="就诊科室" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.jobOfficeName }}
            </template>
          </el-table-column>
          <el-table-column label="就诊诊室" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.workAddressName }}
            </template>
          </el-table-column> -->
          <el-table-column label="就诊类型" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.visitType }}
            </template>
          </el-table-column>
          <el-table-column label="缴费内容" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.payContent }}
            </template>
          </el-table-column>
          <el-table-column label="卡状态" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.myCardList }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="挂号费(元)" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.registerPrice }}
            </template>
          </el-table-column> -->
          <el-table-column label="挂号时长" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.afterGuidanceTime }}
            </template>
          </el-table-column>
          <el-table-column label="缴费时长" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.waitPayTime }}
            </template>
          </el-table-column>
          <el-table-column label="就诊状态" width="150" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusFilter }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="操作" align="center" width="400" >
            <template slot-scope="scope">
              <el-button type="primary" @click="optionPay(scope.row)">缴费操作</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="->, total, prev, pager, next"
          :total="this.total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="clickCurPage"
          >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        :closable="item.isClose == true"
      >
        <!-- patient detail -->
        <div >
          <el-container>
            <el-main>
              <div>
                <div class="patient-base-info" style="font-size: 16px;top: 84px;height: 100px;line-height: 105px;"></div>
                <el-collapse class="patient-base-info" >
                  <el-collapse-item name="1">
                    <template slot="title">
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">基础信息: </span>
                          <span class="main-head-title">
                            {{item.content.code + ' '}}
                            {{item.content.name + ' '}}
                            {{item.content.sex + ' '}}
                            {{item.content.age + '周岁 /'}}
                            {{'手机尾号:'+ item.content.phone + ' /'}}
                            {{'身份证号:'+ item.content.idCard + ' /'}}
                            {{'出生日期:'+ item.content.birthday + ' '}}{{item.content.birthdayType | birthdayTypeFilter}}{{' /'}}
                            {{'会员等级:'}}{{item.content.vipLevel?item.content.vipLevel:'V0' }}
                          </span>
                        </el-col>
                      </el-row>
                    </template>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">就诊信息: </span>
                          <span class="main-head-title">
                            就诊信息内容
                          </span>
                          </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">卡券信息: </span>
                          <span class="main-head-title">卡券信息内容 </span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">用药信息: </span>
                          <span class="main-head-title">用药信息内容 </span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">预案信息: </span>
                          <span class="main-head-title">预案信息内容</span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">诊断信息: </span>
                          <span class="main-head-title">诊断信息内容</span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">就诊习惯: </span>
                          <span class="main-head-title">就诊习惯内容</span>
                        </el-col>
                      </el-row>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <el-tabs v-model="item.content.patientTabsValue" type="border-card" closable @tab-remove="(targetName) => removePatientTab(targetName, item.content)">
                <el-tab-pane
                  v-for="patientTab in item.content.patientTabs"
                  :key="patientTab.name"
                  :label="patientTab.title"
                  :name="patientTab.name"
                >
                  <div v-if="item.content.patientTabsValue == '缴费处置'">
                    <el-collapse v-model="item.content.visitActiveName" >
                      <div class="activity-box">
                        <el-collapse value="1" style="width: 45%" >
                          <el-collapse-item name="1" >
                            <template slot="title">
                              <el-row :gutter=10>
                                <el-col :span=24>
                                  <span class="main-head-title">会员卡包</span>
                                </el-col>
                              </el-row>
                            </template>
                            <!-- 储值卡 -->
                            <el-row v-if="item.content.storedCard" :gutter=10>
                              <el-col :span=24>
                                <span class="main-head-title">{{'储值卡('}} {{ item.content.storedCard.status | cardStatusFilter  }} {{'), '}}</span>
                                <span class="main-head-title">
                                  余额： {{ item.content.storedCard.balance + ' 元 ' }}
                                </span>
                                </el-col>
                            </el-row>
                            <!-- 期限卡 -->
                            <el-row :gutter=10 v-if="item.content.limitTimeCardList && item.content.limitTimeCardList.length != 0" v-for="limitTimeCard in item.content.limitTimeCardList" :key="limitTimeCard.id">
                              <el-col :span=24>
                                <span class="main-head-title">{{'期限卡('}} {{ limitTimeCard.status | cardStatusFilter  }} {{'), '}} </span>
                                <span class="main-head-title">
                                  到期时间: {{ limitTimeCard.endTime }}
                                </span>
                                </el-col>
                            </el-row>
                            
                          </el-collapse-item>
                        </el-collapse>
                        
                        <el-collapse value="1" style="width: 45%" >
                          <el-collapse-item name="1" >
                            <template slot="title">
                              <el-row :gutter=10>
                                <el-col :span=24>
                                  <span class="main-head-title">活动</span>
                                </el-col>
                              </el-row>
                            </template>
                          </el-collapse-item>
                        </el-collapse>
                      </div>
                      <el-collapse-item name="办卡">
                        <template #title>
                          <span style="font-size: 20px;font-weight: 600">办卡</span>
                        </template>
                        <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.buyCardList"
                            element-loading-text="Loading"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                            :cell-style="{padding: '8px 0', height: '50px'}"
                          > 
                            <el-table-column label="序号" align="center" width="50">
                              <template slot-scope="subDrugScope">
                                <div>{{ subDrugScope.$index+1 }}</div>
                                <el-button v-if="subDrugScope.$index != item.content.buyCardList.length - 1 " class="del-btn"  type="danger" icon="el-icon-delete" circle @click="delDrug(subDrugScope.$index, item.content.buyCardList, item.content)"></el-button> 
                              </template>
                            </el-table-column>
                            <el-table-column :label="'卡券商品名称'" align="center" width="140">
                              <template slot-scope="subDrugScope">
                                <el-select size="mini" v-model="subDrugScope.row.id" placeholder="请选择" >
                                  <el-option
                                    v-for="card in item.content.cardList"
                                    :key="card.cardId"
                                    :label="card.cardName"
                                    :value="card.cardId"
                                    @click.native="selectCard(subDrugScope.row, card, item.content)"
                                    >
                                  </el-option>
                                </el-select>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单价'" align="center" width="75" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.unitPrice }}
                              </template>
                            </el-table-column>
                            <el-table-column label="数量" align="center" width="90">
                              <template slot-scope="subDrugScope">
                                <el-input size= "mini" style="width: 60px" type="Number" min=1 placeholder="请输入" v-model="subDrugScope.row.realQuantity" @input="inputRealQuantity(subDrugScope.row)"></el-input>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单品合计金额'" align="center" width="100" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.realSalePrice }}
                              </template>
                            </el-table-column>
                            <el-table-column :label="'备注'" align="center" width="140" >
                              <template slot-scope="subDrugScope">
                                <div class="first-row">
                                  <el-popover
                                    v-model="subDrugScope.row.visible"
                                    v-if = "subDrugScope.row.type == 2"
                                    placement="right"
                                    width="180"
                                    trigger="click"
                                    >
                                    <div class="drugs-item" >
                                      <div >开始日期</div>
                                      <el-date-picker 
                                        style="width: 150px;"
                                        size="mini"
                                        v-model="subDrugScope.row.startDate"
                                        >
                                      </el-date-picker>
                                    </div>
                                    <br>
                                    <br>
                                    <el-button type="primary" size="small" @click="changeStartDate(subDrugScope.row)" >确定</el-button>
                                    <el-button @click="subDrugScope.row.visible = false" size="small" >取消</el-button>
                                    
                                    <el-button slot="reference" size="mini">选择开始日期</el-button>
                                  </el-popover>
                                </div>
                                <span class="second-row" style="left: 3px;" v-if="subDrugScope.row.type == 2" >{{ subDrugScope.row.startDateStr }}</span>

                              </template>
                            </el-table-column>
                            <el-table-column :label="'使用说明'" align="center" width="200" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.description }}
                              </template>
                            </el-table-column>
                            
                          </el-table>
                        <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                          <el-button type="primary" @click="confirmCard(item.content)" :disabled="item.content.status == 5 || item.content.status == 6">办卡提交</el-button>
                        </div>
                      </el-collapse-item>

                      <el-collapse-item  name="缴费">
                        <template #title>
                          <span style="font-size: 20px;font-weight: 600">缴费</span>
                        </template>
                        <!-- 办卡支付金额 -->
                        <el-divider content-position="left">办卡支付金额</el-divider>
                        <table>
                          <tr>
                            <th >产品</th>
                            <th >产品金额</th>
                            <th >收费途径</th>
                            <th >收费金额</th>
                          </tr>
                          <tr>
                              <th>卡</th>
                              <th>{{ item.content.payableAmountInfo.cardAmount ? item.content.payableAmountInfo.cardAmount : 0 }}</th>
                              <th>现金</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.cashAmount" @input="inputPaidCardAmount(item.content.cardPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>微信</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.wechatAmount" @input="inputPaidCardAmount(item.content.cardPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>支付宝</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.alipayAmount" @input="inputPaidCardAmount(item.content.cardPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>外协卡</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.outCardAmount" @input="inputPaidCardAmount(item.content.cardPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>免费</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.freeAmount" @input="inputPaidCardAmount(item.content.cardPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                        </table>
                        <table>
                          <tr>
                            <th >办卡应收合计：</th>
                            <th >{{ item.content.payableAmountInfo.payableCardAmount }}</th>
                          </tr>
                          <tr>
                            <th >办卡实收合计：</th>
                            <th >{{ item.content.cardPayInfo.realPaidCardAmount }}</th>
                          </tr>
                        </table>
                        
                        <!-- 处方支付金额 -->
                        <el-divider content-position="left">处方支付金额</el-divider>
                        <table>
                          <tr>
                            <th >产品</th>
                            <th >产品金额</th>
                            <th >收费途径</th>
                            <th >收费金额</th>
                          </tr>
                          <tr>
                              <th>整装</th>
                              <th>{{ item.content.payableAmountInfo.packageAmount }}</th>
                              <th>储值卡</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.storedCardAmount" @input="inputPaidDrugAmount(item.content.drugPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th>分装</th>
                              <th>{{ item.content.payableAmountInfo.subPackageAmount }}</th>
                              <th>期限卡</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 v-model="item.content.drugPayInfo.limitCardFreeAmount" :disabled="true">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th>检查</th>
                              <th>{{ item.content.payableAmountInfo.inspectionAmount }}</th>
                              <th>现金</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.cashAmount" @input="inputPaidDrugAmount(item.content.drugPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>微信</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.wechatAmount" @input="inputPaidDrugAmount(item.content.drugPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>支付宝</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.alipayAmount" @input="inputPaidDrugAmount(item.content.drugPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>外协卡</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.outCardAmount" @input="inputPaidDrugAmount(item.content.drugPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <th></th>
                              <th></th>
                              <th>免费</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.freeAmount" @input="inputPaidDrugAmount(item.content.drugPayInfo)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                        </table>
                        <table>
                          <tr>
                            <th >商品应收合计：</th>
                            <th >
                              {{ item.content.payableAmountInfo.payableDrugAmount }}
                              {{  '+ (期限卡减免' + item.content.drugPayInfo.limitCardFreeAmount + ')' }}
                            </th>
                          </tr>
                          <tr>
                            <th >商品实收合计：</th>
                            <th >
                              {{ item.content.drugPayInfo.realPaidDrugAmount }}<br/>
                              {{ '(储值卡支付' + item.content.drugPayInfo.storedCardAmount + ')' }}<br/>
                              {{ '(现场支付' }}
                              {{ (Number(item.content.drugPayInfo.realPaidDrugAmount) - Number(item.content.drugPayInfo.storedCardAmount)).toFixed(2) + ')' }}
                            </th>
                          </tr>
                        </table>
                        <!-- 汇总 -->
                        <el-divider content-position="left">汇总</el-divider>
                        <table>
                          <tr>
                            <th >收费途径</th>
                            <th >收费金额</th>
                          </tr>
                          <tr>
                              <th>卡</th>
                              <th>{{ item.content.drugPayInfo.storedCardAmount }}</th>
                          </tr>
                          <tr>
                              <th>现金</th>
                              <th>{{ Number(item.content.cardPayInfo.cashAmount) + Number(item.content.drugPayInfo.cashAmount) }}</th>
                          </tr>
                          <tr>
                              <th>微信</th>
                              <th>{{ Number(item.content.cardPayInfo.wechatAmount) + Number(item.content.drugPayInfo.wechatAmount) }}</th>
                          </tr>
                          <tr>
                              <th>支付宝</th>
                              <th>{{ Number(item.content.cardPayInfo.alipayAmount) + Number(item.content.drugPayInfo.alipayAmount) }}</th>
                          </tr>
                          <tr>
                              <th>外协卡</th>
                              <th>{{ Number(item.content.cardPayInfo.outCardAmount) + Number(item.content.drugPayInfo.outCardAmount) }}</th>
                          </tr>
                          <tr>
                              <th>免费</th>
                              <th>{{ Number(item.content.cardPayInfo.freeAmount) + Number(item.content.drugPayInfo.freeAmount) }}</th>
                          </tr>
                        </table>
                        <table>
                          <tr>
                            <th >应收合计：</th>
                            <th >{{ Number(item.content.payableAmountInfo.payableCardAmount) + Number(item.content.payableAmountInfo.payableDrugAmount) }}</th>
                          </tr>
                          <tr>
                            <th >实收合计：</th>
                            <th >
                                {{ Number(item.content.cardPayInfo.realPaidCardAmount) + Number(item.content.drugPayInfo.realPaidDrugAmount) - Number(item.content.drugPayInfo.storedCardAmount) }}
                                {{ ' (储值卡支付' + item.content.drugPayInfo.storedCardAmount + ')' }}
                            </th>
                          </tr>
                        </table>
                        <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                          <el-button type="primary" @click="confirmPaid(item.content)" :disabled="item.content.status == 5 || item.content.status == 6">缴费提交</el-button>
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </el-tab-pane>
              </el-tabs>

            </el-main>
            <el-aside width="220px">
              <el-menu
                @select="(key, keyPath) => handleMenuSelect(key, keyPath, item.content)" 
                default-active="2"
                :default-openeds="defaultOpen"
                class="el-menu-vertical-demo"
                @open="handleOpen"
                @close="handleClose">
                <el-submenu index="会员管理" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员管理</span>
                  </template>
                    <el-menu-item index="会员基础信息查询" style="font-size: 14px">会员基础信息查询</el-menu-item>
                </el-submenu>
                <el-submenu index="缴费处置" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">缴费处置</span>
                  </template>
                    <el-menu-item index="办卡" style="font-size: 14px">办卡</el-menu-item>
                    <el-menu-item index="缴费" style="font-size: 14px">缴费</el-menu-item>
                </el-submenu>
                <el-submenu index="会员就诊记录查询" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员就诊记录查询</span>
                  </template>
                    <el-menu-item index="会员就诊记录查询" style="font-size: 14px">会员就诊记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="缴费/卡/券" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">缴费/卡/券</span>
                  </template>
                    <el-menu-item index="会员缴费/卡/券记录查询" style="font-size: 14px">会员缴费/卡/券记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="租借药盒" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">租借药盒</span>
                  </template>
                    <el-menu-item index="会员租借药盒记录查询" style="font-size: 14px">会员租借药盒记录查询</el-menu-item>
                </el-submenu>
              </el-menu>
            </el-aside>
          </el-container>
        </div>

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>

import { getList } from '@/api/guidance'
import { getList as getPatientList} from '@/api/patient'
import { GuidanceStatusEnum } from '@/enums/guidanceStatusEnum.js'
import { CardEnum } from '@/enums/CardEnum.js'
import { getList as getCardList } from '@/api/card'
import { getList as getMyCardList, add as addUserCard } from '@/api/patientCard'
import { getVisitAmount, add as addPaid } from '@/api/paid'
import { dateToString, addDate } from '../../utils/dateUtil'
import Decimal from 'decimal.js';

export default {
  name: "Paid",
  filters: {
    statusColorFilter(status) {
      const statusMap = ['', '', '', '', '', 'success', 'info']
      return statusMap[status]
    },
    birthdayTypeFilter(status) {
      const statusMap = ['', '阳', '阴']
      return statusMap[status]
    },
    statusFilter(status) {
      const statusMap = ['候诊', '就诊中', '待检查', '待缴费', '待取药', '已完成', '中止']
      return statusMap[status]
    },
    cardStatusFilter(status) {
      const statusMap = ['未开通', '可用', '不可用']
      return statusMap[status]
    }
  },
  data() {
    const validateSource = (rule, value, callback) => {
      if (!value) callback(new Error('请输入名称')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加来源',
      depts:[],
      formRules: {
        source: [{ required: true, trigger: 'blur', validator: validateSource }],
      },
      editableTabsValue: '缴费列表',
      editableTabs: [],
      defaultOpen: ['会员管理', '诊中处置', '会员就诊记录查询', '缴费/卡/券', '租借药盒'],
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      // var workAddressId = loginInfo.loginWorkAddress.id
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      console.log("loginInfo", loginInfo)
      console.log("GuidanceStatusEnum.PAYING", GuidanceStatusEnum.PAYING)
      getList({currentPage: this.currentPage, pageSize: this.pageSize, deptId: deptId, jobOfficeId: jobOfficeId, status: GuidanceStatusEnum.PAYING}).then(res=>{
        console.log(res.data)
        this.list = res.data.records
        this.noMasterDoctorNum = this.list.filter(item=> !item.doctorId).length
        this.doneWaitingNum = this.list.filter(item=> item.remainderTime == 0).length
        this.noInspectionNum = this.list.filter(item=> !item.masterDoctor).length
        this.noCheckNum = this.list.filter(item=> !item.masterDoctor).length
        this.noInfoNum = this.list.filter(item=> !item.masterDoctor).length
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    optionPay(visit) {
      getPatientList({name: visit.patientCode, currentPage: 1, pageSize: 1}).then(res=> {
        console.log("get patient list res===>", res)
        var patient = res.data.records[0]
        patient.guidanceCode = visit.guidanceCode
        patient.status = visit.status
        var list = this.editableTabs.filter(item => item.name == patient.code)
        this.initPatientVisitData(patient, list)
      })
    },
    async initPatientVisitData(patient, list) {
      if(list.length != 0) {
        this.editableTabsValue = patient.code
        return
      }
      this.$set(patient, 'patientTabsValue', '缴费处置')
      this.$set(patient, 'patientTabs', [{
        title: '缴费处置',
        name: '缴费处置',
        content: {}
      }])
      // 先mock 卡数据 TODO  卡功能完善后从后端取值
      this.$set(patient, 'visitActiveName', '办卡')
      // 获取卡列表
      const cardListRes = await getCardList()
      console.log('cardListRes.data', cardListRes.data)
      this.$set(patient, 'cardList', cardListRes.data)
      // 初始化支付对象
      // 应收
      this.$set(patient, 'payableAmountInfo', {cardAmount: 0, subPackageAmount: 0, packageAmount: 0, inspectionAmount: 0, payableCardAmount: 0, payableDrugAmount: 0})
      // 实收
      this.$set(patient, 'cardPayInfo', {cashAmount: 0, wechatAmount: 0, alipayAmount: 0, outCardAmount: 0, freeAmount: 0, realPaidCardAmount: 0})
      this.$set(patient, 'drugPayInfo', {limitCardFreeAmount: 0, storedCardAmount: 0, cashAmount: 0, wechatAmount: 0, alipayAmount: 0, outCardAmount: 0, freeAmount: 0, realPaidDrugAmount: 0})


      const myCardListRes = await getMyCardList({patientId: patient.id})
      console.log('myCardListRes', myCardListRes)
      // const tmpBuyCardList = myCardListRes.data.filter(card => card.status == 0)
      // for (const element of tmpBuyCardList) {
      //   const rule = JSON.parse(element.cardRule)
      //   element.id = element.cardId
      //   element.name = element.cardName
      //   element.unitPrice = rule.amount
      //   element.realQuantity = 1
      //   element.realSalePrice = rule.amount
      //   element.rule = element.rule
      //   element.type = element.cardType
      // }
      // tmpBuyCardList.push({}) // 添加空行（添加用）
      this.$set(patient, 'buyCardList', [{}])
      // 期限卡可以办理多个
      const limitTimeCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.LIMIT_DATE_CARD)
      this.$set(patient, 'limitTimeCardList', limitTimeCardList)
      // 储值卡每个用户只有一个
      const storedCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.STORED_CARD)
      this.$set(patient, 'storedCard', storedCardList[0])
      // 需缴费金额
      getVisitAmount({guidanceCode: patient.guidanceCode, patientId: patient.id}).then(res=> {
        console.log(res)
        this.$set(patient.payableAmountInfo, 'cardAmount', res.data.cardAmount)
        this.$set(patient.drugPayInfo, 'limitCardFreeAmount', res.data.limitCardFreeAmount)
        this.$set(patient.payableAmountInfo, 'subPackageAmount', res.data.subPackageDrugAmount)
        this.$set(patient.payableAmountInfo, 'packageAmount', res.data.packageDrugAmount)
        this.$set(patient.payableAmountInfo, 'inspectionAmount', res.data.inspectionAmount)
        this.$set(patient.payableAmountInfo, 'payableCardAmount', res.data.cardAmount)
        this.$set(patient.payableAmountInfo, 'payableDrugAmount', new Decimal(res.data.inspectionAmount).plus(new Decimal(res.data.packageDrugAmount)).plus(new Decimal(res.data.subPackageDrugAmount)).toNumber())
      })

      this.editableTabs.push({
        title: patient.name,
        name: patient.code,
        content: patient,
        isClose: true
      })
      this.editableTabsValue = patient.code
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      if(this.editableTabs.length == 0) this.editableTabsValue = '缴费列表'
    },
    /** patient detail page function */
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    handleMenuSelect(key, keyPath, patient) {
      console.log(keyPath)
      var tabValue = keyPath[0]
      console.log(tabValue)
      this.$set(patient, 'visitActiveName', keyPath[1])
      var list = patient.patientTabs.filter(item => item.name == tabValue)
      if(list.length != 0) {
        patient.patientTabsValue = tabValue
        return
      }

      patient.patientTabs.push({
        title: tabValue,
        name: tabValue,
        content: {}
      })
      patient.patientTabsValue = tabValue
    },
    delDrug(index, list, patient) {
      console.log('DEL drug LIST', list)
      const card = list[index]
      console.log('del card', card)
      this.$confirm('删除 '+ card.name + ' x ' + card.realQuantity + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        list.splice(index, 1)
        // this.updateSubPackageReports(patient)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
    selectCard(curCard, cardRecord, patient) {
      console.log('patient--', patient)
      const rule = JSON.parse(cardRecord.rule)
      console.log('rule--', rule)
      // 如果是修改则不加一行
      if(!curCard.unitPrice) {
        patient.buyCardList.push({})
      }
      this.$set(curCard, 'type', cardRecord.type)
      this.$set(curCard, 'rule', cardRecord.rule)
      this.$set(curCard, 'unitPrice', rule.amount)
      this.$set(curCard, 'name', cardRecord.name)
      this.$set(curCard, 'realQuantity', 1)
      this.$set(curCard, 'realSalePrice', rule.amount)
    },
    inputRealQuantity(row) {
      if(row.realQuantity > 99) this.$set(row, 'realQuantity', 0)
      this.checkNumInput(row, 'realQuantity', row.realQuantity)
      this.$set(row, 'realSalePrice', (row.realQuantity * row.unitPrice).toFixed(2))
    },
    checkNumInput(obj, prop, content) {
      // 判空
      if(!content) this.$set(obj, prop, 0)
      // 删除0开头
      this.$set(obj, prop, Number(content))
      // 负数时改为0
      if(!content) this.$set(obj, prop, 0)
    },
    async confirmCard(patient) {
      console.log('confirm patient', patient)
      // 办卡
      console.log('guidance.buyCardList', patient.buyCardList)
      this.$confirm('确定办理', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const reqBuyCardList = JSON.parse(JSON.stringify(patient.buyCardList.slice(0, -1)))  // 入参将最后一个添加行数据截掉
        if(!this.checkCardConfirm(reqBuyCardList)) return

        for (const element of reqBuyCardList) {
          element.cardId = element.id
          element.cardName = element.name
          element.cardRule = element.rule
          element.cardType = element.type
          element.status = 0
        }
        const res = await addUserCard({patientId: patient.id, userCardList: reqBuyCardList})
        console.log('add userCardRes', res)
        const myCardListRes = await getMyCardList({patientId: patient.id})
        console.log('myCardListRes', myCardListRes)
        // 期限卡可以办理多个
        const limitTimeCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.LIMIT_DATE_CARD)
        this.$set(patient, 'limitTimeCardList', limitTimeCardList)
        // 储值卡每个用户只有一个
        const storedCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.STORED_CARD)
        this.$set(patient, 'storedCard', storedCardList[0])
        // 提交办卡后，重新获取需缴费金额
        getVisitAmount({guidanceCode: patient.guidanceCode, patientId: patient.id}).then(res=> {
          console.log(res)
          this.$set(patient.payableAmountInfo, 'cardAmount', res.data.cardAmount)
          this.$set(patient.payableAmountInfo, 'limitCardFreeAmount', res.data.limitCardFreeAmount)
          this.$set(patient.payableAmountInfo, 'subPackageAmount', res.data.subPackageDrugAmount)
          this.$set(patient.payableAmountInfo, 'packageAmount', res.data.packageDrugAmount)
          this.$set(patient.payableAmountInfo, 'inspectionAmount', res.data.inspectionAmount)
        })
        this.$message({
          type: 'success',
          message: '办理成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    checkCardConfirm(buyCardList) {
      for (const buyCard of buyCardList) {
        if(buyCard.unitPrice) {
          if(!buyCard.realQuantity || buyCard.realQuantity == 0) {
            this.$alert('请填写' + buyCard.name + '数量', '错误', {
              confirmButtonText: '确定',
              type: 'error',
            });
            return false
          }
          if(buyCard.type == 2) {
            if(!buyCard.startDate) {
              this.$alert('请选择' + buyCard.name + '开始日期', '错误', {
                confirmButtonText: '确定',
                type: 'error',
              });
              return false
            }
          }
        }
      }
      return true
    },
    async confirmPaid(patient) {
      // 缴费
      if(!this.checkPaid(patient)) return
      console.log('guidance.buyCardList', patient.buyCardList)
      this.$confirm('确定办理', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var reqDto = {
          guidanceCode: patient.guidanceCode,
          patientId: patient.id,
          payableAmountInfo: patient.payableAmountInfo,
          cardPayInfo: patient.cardPayInfo,
          drugPayInfo: patient.drugPayInfo,
        }
        console.log('paid reqDto', reqDto)
        const addPaidRes = await addPaid(reqDto)
        console.log('addPaidRes', addPaidRes)

        this.$message({
          type: 'success',
          message: '办理成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    checkPaid(patient) {
      if (Number(patient.payableAmountInfo.payableCardAmount) != Number(patient.cardPayInfo.realPaidCardAmount)) {
        this.$alert('办卡金额输入有误', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      if (Number(patient.payableAmountInfo.payableDrugAmount) != Number(patient.drugPayInfo.realPaidDrugAmount)) {
        this.$alert('商品金额输入有误', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      return true
    },
    changeStartDate(row) {
      console.log('row', row)
      if(row.type == 2) {
        if(!row.startDate) {
          this.$set(row, 'startDateStr', undefined)
          row.visible = false
          return
        }
        const rule = JSON.parse(row.rule)
        const endDate = addDate(row.startDate, 'day', Number(rule.limitDays))
        rule.endTime = endDate
        this.$set(row, 'startDateStr', dateToString(row.startDate, 1).substring(2) + ' - ' + dateToString(endDate, 1).substring(2))
        row.visible = false
      }
    },
    inputPaidDrugAmount(drugPayInfo) {
      this.checkNumInput(drugPayInfo, 'storedCardAmount', drugPayInfo.storedCardAmount)
      this.checkNumInput(drugPayInfo, 'cashAmount', drugPayInfo.cashAmount)
      this.checkNumInput(drugPayInfo, 'wechatAmount', drugPayInfo.wechatAmount)
      this.checkNumInput(drugPayInfo, 'alipayAmount', drugPayInfo.alipayAmount)
      this.checkNumInput(drugPayInfo, 'outCardAmount', drugPayInfo.outCardAmount)
      this.checkNumInput(drugPayInfo, 'freeAmount', drugPayInfo.freeAmount)
      const totalAmount = new Decimal(drugPayInfo.cashAmount).plus(new Decimal(drugPayInfo.storedCardAmount)).plus(new Decimal(drugPayInfo.wechatAmount)).plus(new Decimal(drugPayInfo.alipayAmount)).plus(new Decimal(drugPayInfo.outCardAmount))
      console.log(totalAmount.toNumber())
      this.$set(drugPayInfo, 'realPaidDrugAmount', totalAmount.toNumber())
    },
    inputPaidCardAmount(cardPayInfo) {
      this.checkNumInput(cardPayInfo, 'cashAmount', cardPayInfo.cashAmount)
      this.checkNumInput(cardPayInfo, 'wechatAmount', cardPayInfo.wechatAmount)
      this.checkNumInput(cardPayInfo, 'alipayAmount', cardPayInfo.alipayAmount)
      this.checkNumInput(cardPayInfo, 'outCardAmount', cardPayInfo.outCardAmount)
      this.checkNumInput(cardPayInfo, 'freeAmount', cardPayInfo.freeAmount)
      const totalAmount = new Decimal(cardPayInfo.cashAmount).plus(new Decimal(cardPayInfo.wechatAmount)).plus(new Decimal(cardPayInfo.alipayAmount)).plus(new Decimal(cardPayInfo.outCardAmount))
      this.$set(cardPayInfo, 'realPaidCardAmount', totalAmount.toNumber())
    },
    checkNumInput(obj, prop, content) {
      // 判空
      if(!content) this.$set(obj, prop, 0)
      // 删除0开头
      this.$set(obj, prop, Number(content))
      // 负数时改为0
      if(!content) this.$set(obj, prop, 0)
    },
  },  
}
</script>

<style lang="scss" scoped>
  .del-btn {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 4px;
  }
  .activity-box {
    display: flex;
    justify-content: space-around;
  }

  .first-row {
    position: absolute;
    top: 8px;
    left: 3px;
    width: 93%;
  }
  
  .second-row {
    position: absolute;
    top: 38px;
    left: 3px;
    width: 93%;
  }
  table {
      border-collapse: collapse;
      width: 30%;
      margin: 20px 0;
      font-family: Arial, sans-serif;
  }
  th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: center;
  }
  th {
      background-color: #f2f2f2;
      font-weight: bold;
  }
  /* 设置列宽 */
  th:nth-child(1) { width: 80px; }  /* 产品列 */
  th:nth-child(2) { width: 80px; } /* 产品金额列 */
  th:nth-child(3) { width: 80px; } /* 收费途径列 */
  th:nth-child(4) { width: 80px; } /* 收费金额列 */

  
  .repair-box ::v-deep .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 93%;
    margin: 0 0
  }

  ::v-deep .el-tabs__item {
    height: 30px;
    line-height: 30px;
  }
  .app-container > ::v-deep .el-tabs--border-card > .el-tabs__header{
    position: fixed;
    z-index: 98;
    top: 84px;
  }

  .el-main > .patient-base-info > .el-collapse {
    position: fixed;
    z-index: 98;
    top: 160px;
    width: 72%
  }
  .el-main > ::v-deep .el-tabs--border-card {
    margin-top: 70px;
  }
  .patient-base-info {
    position: fixed;
    z-index: 97;
    background-color: #fff;
    width: 72%;
    padding: 0 16px;
  }

</style>